package metr;

import connect.DBUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.util.Vector;

public class StockAlertFrame extends JFrame {
    private JTable alertTable;
    private DefaultTableModel tableModel;

    public StockAlertFrame() {
        setTitle("库存预警");
        setSize(800, 600);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new BorderLayout());

        // 顶部说明
        JLabel infoLabel = new JLabel("以下商品库存低于最低库存或高于最高库存", JLabel.CENTER);
        infoLabel.setForeground(Color.RED);
        panel.add(infoLabel, BorderLayout.NORTH);

        // 中间表格区域
        tableModel = new DefaultTableModel();
        tableModel.addColumn("商品ID");
        tableModel.addColumn("商品名称");
        tableModel.addColumn("规格");
        tableModel.addColumn("当前库存");
        tableModel.addColumn("最低库存");
        tableModel.addColumn("最高库存");
        tableModel.addColumn("状态");

        alertTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(alertTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        add(panel);

        // 加载预警数据
        loadAlertData();
    }

    private void loadAlertData() {
        tableModel.setRowCount(0);

        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM products WHERE stock_quantity < min_stock OR stock_quantity > max_stock")) {

            while (rs.next()) {
                Vector<Object> row = new Vector<>();
                row.add(rs.getInt("product_id"));
                row.add(rs.getString("name"));
                row.add(rs.getString("specification"));

                int stock = rs.getInt("stock_quantity");
                int minStock = rs.getInt("min_stock");
                int maxStock = rs.getInt("max_stock");

                row.add(stock);
                row.add(minStock);
                row.add(maxStock);

                if (stock < minStock) {
                    row.add("库存不足");
                } else if (stock > maxStock) {
                    row.add("库存过剩");
                } else {
                    row.add("正常");
                }

                tableModel.addRow(row);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载预警数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}